<template>
  <BoTable
    :columns="columns"
    :request="list"
    ref="tableRef"
    height="auto"
    :row-selection="rowSelection"
    row-key="sourceTotalId"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增 </Button>
        <Button @click="onDelete(null)" :disabled="!selectKeys.length">
          删除
        </Button>
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="item">
    <template #label1>
      <div class="custom_title">连接信息</div>
    </template>
    <template #label2>
      <div class="custom_title">授权信息</div>
    </template>
    <template #label3>
      <div class="custom_title">主题服务</div>
    </template>
  </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Modal, Space, Switch, message } from 'ant-design-vue';
import { add, connection, detail, edit, list, remove } from './api';

const sourceEnum = {
  1: {
    text: 'MQTT',
    status: 'error',
  },
  2: {
    text: 'MQTT',
    status: 'error',
  },
};
const selectKeys = ref<number[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});
const sourceType = ref('2');
const text = computed(() => {
  return sourceType.value === '2' ? '主题' : '服务';
});
const uname = computed(() => {
  return sourceType.value != '4' ? '用户名' : '认证ID';
});
const tableRef = ref();
const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '信息源',
    dataIndex: 'affiliation',
    hideInSearch: true,
  },
  {
    title: '连接类型',
    dataIndex: 'source',
    hideInSearch: true,
    valueEnum: { ...sourceEnum },
  },
  {
    title: '连接地址',
    dataIndex: 'code1',
    hideInSearch: true,
    customRender({ record }) {
      return <span>{record.childs[0]?.ip}</span>;
    },
  },
  {
    title: '连接端口',
    dataIndex: 'code4',
    hideInSearch: true,
    customRender({ record }) {
      return <span>{record.childs[0]?.port}</span>;
    },
  },
  {
    title: '连接状态',
    dataIndex: 'isConnSuccess',
    hideInSearch: true,
    valueType: 'status',
    valueEnum: {
      0: {
        text: '已连接',
        status: 'success',
      },
      1: {
        text: '未连接',
        status: 'danger',
      },
    },
  },
  {
    title: '是否连接',
    dataIndex: 'isConnSuccess',
    hideInSearch: true,
    customRender: ({ text, record }) => {
      return (
        <Switch
          checkedValue={'0'}
          unCheckedValue={'1'}
          v-model:checked={text}
          onChange={(e) => onChange(e, record)}
        ></Switch>
      );
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    actions: [
      {
        text: '查看',
        onClick(record) {
          onView(record);
        },
      },
      {
        text: '删除',
        onClick(record) {
          onDelete(record);
        },
      },
    ],
  },
]);

const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
});

const onView = async (record) => {
  const result: any = await detail(record.sourceTotalId);
  sourceType.value = ['1', '2'].includes(result.source) ? '2' : result.source;
  console.log(result, 'result');

  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    request: async (params: any) => {
      await edit(params);
      await connection({ sourceTotalId: record.sourceTotalId });

      tableRef.value.refresh();
    },
    defaultValue: result.data,
  });
};
const onAdd = () => {
  open({
    title: '新增',
    request: async (params: any) => {
      await add(params);
      tableRef.value.refresh();
    },
    defaultValue: {},
  });
};
const item = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'label1',
    valueType: 'input',
  },
  {
    title: '连接类型',
    dataIndex: 'source',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: false,
          message: '请选择连接类型',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择连接类型',
      options: [{ label: 'MQTT', value: '2' }],
    },
  },
  {
    title: '来源机构',
    dataIndex: 'affiliation',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入来源机构',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入来源机构',
    },
  },
  {
    title: '服务器地址',
    dataIndex: 'ip',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入服务器地址',
          trigger: 'blur',
        },
        {
          max: 15,
          message: '服务器地址应在15个字符以内',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入服务器地址',
    },
  },
  {
    title: '端口',
    dataIndex: 'port',
    valueType: 'inputNumber',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入端口号',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入端口号',
    },
  },
  {
    title: '',
    dataIndex: 'label2',
    valueType: 'input',
  },
  {
    title: 'Client ID',
    dataIndex: 'clientId',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入Client ID',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入Client ID',
    },
  },
  {
    title: uname.value,
    dataIndex: 'uname',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: `请输入${uname.value}`,
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: `请输入${uname.value}`,
      autocomplete: 'off',
    },
  },
  {
    title: '密码',
    dataIndex: 'pwd',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入密码',
      type: 'password',
      autocomplete: 'off',
    },
  },
  {
    title: '',
    dataIndex: 'label3',
    valueType: 'input',
  },
  {
    title: `地震预警${text.value}`,
    dataIndex: 'warningService',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: false,
          message: `请输入地震预警${text.value}`,
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: `请输入地震预警${text.value}`,
    },
  },
  {
    title: `地震速报${text.value}`,
    dataIndex: 'quickReportService',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: false,
          message: `请输入地震速报${text.value}`,
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: `请输入地震速报${text.value}`,
    },
  },
  {
    title: `地震反馈${text.value}`,
    dataIndex: 'feedbackService',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: false,
          message: `请输入地震反馈${text.value}`,
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: `请输入地震反馈${text.value}`,
    },
  },
]);

const onChange = (status, record) => {
  const text = record.isConnSuccess == '0' ? '是否断开？' : '是否连接？';
  Modal.confirm({
    title: '系统提示',
    content: text,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const sourceTotalId = record.sourceTotalId;
        await connection({ sourceTotalId });
        tableRef.value.refresh();
      } catch (error) {
        tableRef.value.refresh();
      }
    },
  });
};

const onDelete = (record: any) => {
  const ids = record ? record.sourceTotalId : selectKeys.value.join(',');
  Modal.confirm({
    title: '删除',
    content: '确定删除当前项吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      await remove(ids);
      tableRef.value.refresh();
    },
  });
};
</script>

<style lang="scss" scoped>
.custom_title {
  padding-left: 10px;
  position: relative;
  &::before {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    content: '';
    width: 3px;
    height: 10px;
    background-color: #40deff;
  }
}
</style>
<route lang="json">
{
  "name": "信息源管理",
  "meta": { "title": "信息源管理" }
}
</route>
